<?php

namespace App\Console\Commands;

use App\Constant\RepayConstant;
use App\Facades\MoneyPlatformRequestFacade;
use App\Jobs\RepayMoneyNotifyJobQueue;
use App\Library\Traits\RepaySmsRemind;
use App\Models\Collection\UserLoanRequest;
use App\Models\RepayRecord;
use App\Models\RepayRecordCommon;
use App\Models\RepayRecordMoney;
use App\Models\RepayRecordMonth;
use App\Models\RepaySummary;
use App\Models\SettingChannel;
use App\Models\User;
use App\Models\UserGlobal;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class RepayDataCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'repay_data:data {action : setRepayData|setSummaryData|setSummaryLoanId|setMoneyNotify|setSummaryStatus|textCollection|setRepayId|setUserRepay|setRepaySuccess|setRepayMoney|setRepayMoney7|setRepayMoney8|setRepayMoney81} {--loan_id=} {--time=} {--record_id=}';
    protected $action;
    /**
     * 对还款的数据进行修复的command
     *
     * @var string
     */
    protected $description = '对还款的数据进行修复的command';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->initAction();
        $this->runAction();
    }

    /**
     * Description: Initialize command action.
     * Author: Gxs
     */
    protected function initAction()
    {
        $this->action = $this->argument('action');

        if (!in_array($this->action, ['setRepayData','setSummaryLoanId','setMoneyNotify','setSummaryStatus','textCollection','setRepayId','setUserRepay','setRepaySuccess','setRepayMoney','setRepayMoney7','setRepayMoney8','setRepayMoney81'])) {
            $this->error("Invalid argument '{$this->action}'. Expected 'month', 'common', 'money', 'help'.");
            exit(1);
        }
    }

    /**
     * Description: Run action.
     * Author: Gxs
     */
    protected function runAction()
    {
        $this->{$this->action}();
    }

    /**
     * Description:修复repay_record_money表的repay_date字段
     * Author:lijiafei
     */
    public function setRepayData(){
        //查询昨天的还款成功记录
        $time = $this->option('time');
        $timearray = explode(':',$time);
        $starttime =  $timearray[0];
        $endtime   = $timearray[1];
        $moneyInfo = RepayRecordMoney::where('status',RepayRecordMoney::STATUS_FOUR)
//            ->whereNull('repay_date')
            ->whereBetween('updated_at',[$starttime,$endtime])
            ->get();
        if(!empty($moneyInfo)){
            foreach ($moneyInfo as $k => $v){
                if(!empty($v)){
                    $loan_id = $v->loan_id;
                    $period = $v->period;
                    if($loan_id && $period && $period != 0){
                        //获取还款计划表
                        $data = RepaySummary::mapMoneyDataFromThirdApi($loan_id,$period);
                        $repay_date = isset($data['actualRepayDate']) ? $data['actualRepayDate'] : null;
                        $repay_date = Carbon::parse($repay_date)->toDateString();
                        if(empty($data) || empty($repay_date)){
                            continue;
                        }
                        if(!empty($repay_date)){
                            if($v->repay_date != $repay_date){
                                dump('loainid:'.$loan_id.'--期数'.$period.'--资方返回还款日期'.$repay_date.'平台记录还款日期'.$v->repay_date);
                                Log::debug('set_repaydata_success', ['message' => 'loainid:'.$loan_id.'--期数'.$period.'--资方返回还款日期'.$repay_date.'平台记录还款日期'.$v->repay_date]);
                                $v->repay_date = $repay_date;
                                $v->save();
                            }
                        }
                    }
                }
            }
        }
        $this->info('执行完成');
    }

    /**
     * Description:把这几天的老光大的数据重新请求资方
     * Author:lijiafei
     */
    public function setMoneyNotify(){
        $info = RepayRecordCommon::where('repay_record_commons.status',RepayRecordCommon::STATUS_FOUR)->where('money_notify_status','<>',RepayRecordCommon::MONEY_NOTIFY_STATUS_FOUR)
            ->where('money_notify_status','<>',RepayRecordCommon::MONEY_NOTIFY_STATUS_TWO)
            ->leftjoin('repay_records','repay_records.id','repay_record_commons.record_id')
            ->leftjoin('repay_summaries','repay_summaries.id','repay_record_commons.summary_id')
            ->where('repay_summaries.loan_channel','LCC201709190009')
            ->where('repay_records.status',RepayRecord::STATUS_FOUR)
            ->whereDate('repay_records.repay_date','>=','2019-02-20')
            ->chunk(1000, function ($info) {
                foreach ($info as $k => $v){
                    if(!empty($v)){
                        RepayMoneyNotifyJobQueue::dispatch($v->record_id);
                    }
                }
            });

    }

    public function setSummaryStatus(){
        $loan_id = $this->option('loan_id');
        if(!empty($loan_id)){
            $summaryInfo = RepaySummary::where('loan_id',$loan_id)->first();
            if(!empty($summaryInfo)){
                $recordInfo = RepayRecord::where('summary_id',$summaryInfo->id)->first();
                $this->setShouDongSuccess($recordInfo);
                //判断当前用户是否还有还款记录
                $summary = RepaySummary::where('uid',$summaryInfo->uid)->where('status',RepaySummary::STATUS_ONE)->first();
                if(!empty($summary)){
                    UserGlobal::where('uid', $summaryInfo->uid)->update(['global_status' => UserGlobal::STATUS_REPAY_INIT]); //全局状态
                }
            }
        }
    }

    /**
     * Description: 设置订单(所有未成功)为成功
     * Author: ljf
     * @param RepayRecord $model
     * @return bool
     */
    public static function setShouDongSuccess($model)
    {
        try {
            DB::beginTransaction();
            $summary_model = RepaySummary::where('id', $model->summary_id)->first();
            RepaySummary::where('id', $model->summary_id)->update([
                'period' => $summary_model->period_count,
                'status' => RepaySummary::STATUS_TWO,
            ]); //summary 摘要表 最终状态变更

            $where = [
                ['summary_id', '=', $model->summary_id],
                ['status', '<>', RepayRecord::STATUS_FOUR],
            ];
            $repay_plan_data = RepaySummary::mapMoneyDataFromThirdApi($summary_model->loan_id); //全部还款计划表
            if (false == $repay_plan_data)
                Log::debug('repay_get_money_result', ['message' => '三方还款计划接口异常,请查看日志']);
            $end_data = end($repay_plan_data);
            //记录总表
            RepayRecord::where($where)->update([
                'status' => RepayRecord::STATUS_FOUR,
                'pay_off' => RepayRecord::PAY_OFF_ONE,
                'repay_date' => Carbon::now(), //实际还款日期
                'repay_type' => RepayRecord::REPAY_TYPE_XIANXIA,//状态改为7 线下提前结清
            ]);

            //资方表
            RepayRecordMoney::where($where)->update([
                'status' => RepayRecord::STATUS_FOUR,
                'apply_time' => Carbon::now(), //实际还款日期
                'status_time' => Carbon::now(), //实际还款日期
                'repay_date' => isset($end_data['actualRepayDate']) ? Carbon::createFromTimeString($end_data['actualRepayDate'])->toDateString() : Carbon::now()->toDateString(), //实际还款日期
                'manage_money' => 0,//提前结清的贷后管理费0
                'type' => RepayRecordMoney::$third_map_type[$end_data['status']],
                'repay_type' => RepayRecord::REPAY_TYPE_XIANXIA,//状态改为7 线下提前结清
            ]);

            //月保费表
            RepayRecordMonth::where($where)->update([
                'status' => RepayRecord::STATUS_FOUR,
                'apply_time' => Carbon::now(), //实际还款日期
                'status_time' => Carbon::now(), //实际还款日期
                'repay_type' => RepayRecord::REPAY_TYPE_XIANXIA,//状态改为7 线下提前结清
            ]);

            //公共平台表
            RepayRecordCommon::where($where)->update([
                'status' => RepayRecord::STATUS_FOUR,
                'apply_time' => Carbon::now(), //实际还款日期
                'status_time' => Carbon::now(), //实际还款日期
                'repay_type' => RepayRecord::REPAY_TYPE_XIANXIA,//状态改为7 线下提前结清
            ]);

            UserGlobal::where('uid', $model->uid)->update(['global_status' => UserGlobal::STATUS_REPAY_OVER]); //全局状态
            DB::commit();
            return true;
        } catch (\Exception $e) {
            print_r($e->getMessage());
            Log::debug('set_all_period_success', ['message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            DB::rollBack();
            return false;
        }
    }

    /**
     * Description:销账的脚本
     * Author:lijiafei
     */
    public function textCollection(){
        $a = <<<heredoc
        [{"phone":"15282120555","repay_date":84,"period":7,"money":"888.18","name":"吴德群"},{"phone":"15619571302","repay_date":84,"period":3,"money":"1447.58","name":"赵文涛"},{"phone":"13853579397","repay_date":144,"period":1,"money":"3000.00","name":"杨学顺"},{"phone":"15310558629","repay_date":101,"period":4,"money":"928.00","name":"杨钧杰"},{"phone":"18690209815","repay_date":42,"period":1,"money":"1285.05","name":"郭丽丽"},{"phone":"13600944922","repay_date":52,"period":1,"money":"2753.69","name":"陈春勇"},{"phone":"13477067073","repay_date":45,"period":1,"money":"977.90","name":"王晶"},{"phone":"13879172528","repay_date":39,"period":2,"money":"5285.97","name":"熊燕"},{"phone":"18996490260","repay_date":22,"period":4,"money":"840.77","name":"龚吉伟"},{"phone":"15986134082","repay_date":36,"period":4,"money":"1200.00","name":"冯志平"},{"phone":"18713385554","repay_date":67,"period":2,"money":"1500.00","name":"赵晓依"},{"phone":"18994055912","repay_date":42,"period":4,"money":"1220.00","name":"王长杨"},{"phone":"18711302017","repay_date":42,"period":1,"money":"2739.01","name":"孙佳晖"},{"phone":"13871366106","repay_date":30,"period":2,"money":"5285.97","name":"周斌"},{"phone":"13357200011","repay_date":34,"period":2,"money":"1306.00","name":"刘语"},{"phone":"13893001117","repay_date":30,"period":1,"money":"1285.05","name":"李藤郁"},{"phone":"15850740291","repay_date":27,"period":2,"money":"2753.69","name":"谭笑露"},{"phone":"13765486623","repay_date":39,"period":1,"money":"2565.00","name":"王崬"},{"phone":"13668067381","repay_date":30,"period":1,"money":"917.90","name":"何海燕"},{"phone":"13911819170","repay_date":30,"period":2,"money":"5285.97","name":"阮志宝"},{"phone":"13913459488","repay_date":32,"period":4,"money":"1376.84","name":"刘孝虎"},{"phone":"15500301588","repay_date":32,"period":4,"money":"1193.26","name":"孙傲"},{"phone":"17614855065","repay_date":42,"period":3,"money":"3363.00","name":"陈明远"},{"phone":"15804304823","repay_date":32,"period":2,"money":"918.00","name":"宋朋"},{"phone":"15128056323","repay_date":56,"period":4,"money":"984.34","name":"胡学平"},{"phone":"15080554708","repay_date":32,"period":4,"money":"1193.26","name":"赖秋秀"},{"phone":"15179208385","repay_date":168,"period":1,"money":"3040.00","name":"胡伟"},{"phone":"18768124347","repay_date":30,"period":1,"money":"2753.69","name":"黄宽"},{"phone":"15906398911","repay_date":30,"period":1,"money":"1286.00","name":"岳健"},{"phone":"13819748441","repay_date":32,"period":2,"money":"1761.99","name":"杨震"},{"phone":"15910271088","repay_date":126,"period":1,"money":"1018.44","name":"李亮"},{"phone":"18376526696","repay_date":34,"period":3,"money":"1232.26","name":"莫淮雄"},{"phone":"13852844489","repay_date":42,"period":1,"money":"2726.01","name":"赵克禹"},{"phone":"18145581565","repay_date":30,"period":1,"money":"2753.69","name":"魏东才"},{"phone":"13557955857","repay_date":32,"period":4,"money":"550.74","name":"韦青良"},{"phone":"13006161275","repay_date":39,"period":9,"money":"377.59","name":"李琪明"},{"phone":"13510426008","repay_date":56,"period":1,"money":"858.44","name":"林树臻"},{"phone":"13708872968","repay_date":32,"period":4,"money":"1193.26","name":"刘嘉宇"},{"phone":"15829203617","repay_date":32,"period":2,"money":"1306.05","name":"李聪聪"},{"phone":"13728710873","repay_date":42,"period":4,"money":"1200.26","name":"刘宝庆"},{"phone":"13947530768","repay_date":144,"period":7,"money":"1720.00","name":"刘丹"},{"phone":"13535566108","repay_date":46,"period":1,"money":"179.20","name":"黄豪婷"}]  
heredoc;
        $phoneArr = json_decode($a,true);
        if(!is_array($phoneArr)){
            return;
        }
        $i=0;
        $unDealWith=[];
        foreach($phoneArr as $phone=>$val){
            $user = User::select('id')->where('phone_num', $val['phone'])->first();
            if(empty($user)){
                continue;
            }
            $recordInfo = RepayRecord::select('repay_records.*')
                ->leftjoin('repay_summaries','repay_summaries.id','repay_records.summary_id')
                ->where('repay_records.period',$val['period'])
                ->where('repay_records.status','<>',RepayRecord::STATUS_FOUR)
                ->where('repay_summaries.uid',$user->id)
                ->where('repay_summaries.status',RepaySummary::STATUS_ONE)
                ->first();
            if(empty($recordInfo)){
                continue;
            }
            $i++;
            $unDealWith[]=$val['phone'];
            $summaryInfo = $recordInfo->relationSummary;
            //区分销帐资方
            $money_channel = '';
            if (RepayConstant::DATA_TYPE_ONE == $summaryInfo->data_type) {
                //新卡贷数据
                $money_channel = self::_writeOffMoneyChannel($summaryInfo->loan_request_id);
            } else if (RepayConstant::DATA_TYPE_TWO == $summaryInfo->data_type) {
                //原卡贷数据
                //老数据区分晋商和新光大
                if (SettingChannel::CHANNEL_OLD_JINSHANG == $summaryInfo->loan_channel) {
                    $money_channel = self::_writeOffMoneyChannel($summaryInfo->loan_request_id);
                } else if (SettingChannel::CHANNEL_OLD_GUANGDA == $summaryInfo->loan_channel) {
                    //销帐后,通知资方
                    $money_channel = RepayConstant::WRITE_OFF_THREE;
                } else {
                    //直接销帐
                    $money_channel = RepayConstant::WRITE_OFF_FOUR;
                }
            }
            $money = $val['money'];//催收的金额
            if(empty($money)){
                continue;
            }
            switch ($money_channel) {
                case RepayConstant::WRITE_OFF_ONE || RepayConstant::WRITE_OFF_TWO: //晋商 或者 光大的
                    //改变自己表的状态
                    $res = RepaySummary::setRepayCurrentStatus($recordInfo,$money);
                    if(!$res){
                        continue;
                    }
                    $data['loanId'] = $summaryInfo->loan_id;
                    if (strstr($data['loanId'],'KD')) {
                        //和资方平台没有关系
                        continue;
                    }
                    $data['currentPeriod'] = $recordInfo->period;
                    $res2 = MoneyPlatformRequestFacade::PayCompensate($data);
                    Log::debug('pay_compensate', ['message' => json_encode($res2,JSON_UNESCAPED_UNICODE)]);
                    $updateRecord = array();
                    if ($res2['flag']) {
                        $res2 = $res2['result'];
                        $updateRecord = [
                            'result_repay_id' => isset($res2['data']['resultRepayId']) ? $res2['data']['resultRepayId'] : '',
                            'trade_no' => \App\Models\RepaySummary::createTradeNo($recordInfo->uid, 'repay_record'),
                            'xz_status' => RepayRecord::COMPENSATE_STATUS_TWO,
                        ];
                    }else{
                        $updateRecord['xz_status'] = RepayRecord::COMPENSATE_STATUS_THREE;
                    }
                    $updateRecord['xz_failure_message'] = json_encode($res2,JSON_UNESCAPED_UNICODE);
                    RepayRecord::where('id',$recordInfo->id)->update($updateRecord);
                    break;
                case RepayConstant::WRITE_OFF_THREE: //老光大
                    //改变自己表的状态
                    $res = RepaySummary::setRepayCurrentStatus($recordInfo,$money);
                    if(!$res){
                        continue;
                    }
                    //主动还款通知资方
                    RepayMoneyNotifyJobQueue::dispatch($recordInfo->id);
                    break;
                case RepayConstant::WRITE_OFF_FOUR: //其他
                    //改变自己表的状态
                    $res = RepaySummary::setRepayCurrentStatus($recordInfo,$money);
                    if(!$res){
                        continue;
                    }
                    $data['loanId'] = $summaryInfo->loan_id;
                    if (strstr($data['loanId'],'KD')) {
                        //和资方平台没有关系
                        continue;
                    }
                    break;
                default:
                    break;
            }
        }
        LOG::debug('all_update',['num'=>$i,'arr'=>$unDealWith]);
    }

    /**
     * Description: 区分销帐资方渠道
     * Author: Gxs
     * @param $loan_request_id
     * @return int|string
     */
    private static function _writeOffMoneyChannel($loan_request_id)
    {
        $money_channel = '';
        $request_channel = UserLoanRequest::where('id', $loan_request_id)
            ->select(['channel'])->value('channel');
        if (RepayConstant::MONEY_CHANNEL_GUANG_DA == $request_channel) {
            $money_channel = RepayConstant::WRITE_OFF_TWO;
        } else if (RepayConstant::MONEY_CHANNEL_JIN_SHANG == $request_channel) {
            $money_channel = RepayConstant::WRITE_OFF_ONE;
        }
        return $money_channel;
    }

    /**
     * Description:通过loan_id推送到队列里面,还款
     * Author:lijiafei
     */
    public function setUserRepay(){
        $loan_id = $this->option('loan_id');
        if(!empty($loan_id)){
            $summaryInfo = RepaySummary::where('loan_id',$loan_id)->first();
            if(!empty($summaryInfo)){
                $record = RepaySummary::getRepaySummaryLog($summaryInfo->uid);
                RepaySummary::setCurrentRepayJob($record->recordOne,RepayRecord::REPAY_TYPE_MANUAL,1);
            }
        }
    }

    public function setRepaySuccess(){
        $record_id = $this->option('record_id');
        $time = $this->option('time');
        if(empty($time)){
            $repay_date = Carbon::now();
        }else{
            $repay_date = Carbon::parse($time);
        }
        if(!empty($record_id)){
            $recordInfo = RepayRecord::where('id',$record_id)->where('status','<>',4)->where('status','<>',2)->first();
            if(!empty($recordInfo)){
                try {
                    $summaryInfo = RepaySummary::where('id',$recordInfo->summary_id)->first();
                    DB::beginTransaction();
                    //最后顺序队列单期还款调用逻辑
                    if ($summaryInfo->period_count == $recordInfo->period) {
                        //最后一期还清
                        RepaySummary::where('id', $recordInfo->summary_id)->update([
                            'period' => $recordInfo->period,
                            'status' => RepayRecord::STATUS_TWO,
                        ]); //summary 摘要表 最终状态变更
                        UserGlobal::where('uid', $recordInfo->uid)->update(['global_status' => UserGlobal::STATUS_REPAY_OVER]); //全局状态
                    } else {
                        RepaySummary::where('id', $recordInfo->summary_id)->update(['period'=>(int)($recordInfo->period + 1),]); //summary表
                        UserGlobal::where('uid', $recordInfo->uid)->update(['global_status' => UserGlobal::STATUS_REPAY_SUCCESS]); //全局状态
                    }

                    //记录总表
                    RepayRecord::where('id', $recordInfo->id)->update([
                        'status' => RepayRecord::STATUS_FOUR,
                        'pay_off' => RepayRecord::PAY_OFF_ONE,
                        'repay_date' => $repay_date->toDateString(), //实际还款日期
                    ]);

                    //公共平台表
                    RepayRecordCommon::where('record_id', $recordInfo->id)
                        ->where('period', $recordInfo->period)
                        ->update([
                            'status' => RepayRecordCommon::STATUS_FOUR,
                            'status_time' => $repay_date->toDateTimeString(), //实际还款日期
                            'apply_time' => $repay_date->toDateTimeString(), //实际还款日期
                        ]);
                    DB::commit();
                    return true;
                } catch (\Exception $e) {
                    Log::debug('set_current_period_success', ['message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
                    DB::rollBack();
                    return false;
                }
            }
        }
    }

    /**
     * Description:修复问题1
     * Author:lijiafei
     */
    public function setRepayMoney(){
        $data = <<<HA
["15203909839","18266062282","15180411856","13418905357","15918465188","17761217517","18808882200","15554363738","13840496061","13787419720","13844941616","15826829527","15093229389","13593241874","13554518512","18094390975","18998937539","13252022322","13578434532","18551105897","13927465129","13220011223","18500344462","18891216189","15679257666","18318842280","13994601068","15057022868","18202859008","17789788078","18788086240","13451466229","18545397670","15001035230","15005080608","15995127042","13359175610","18673752211","13887193409","18606030311","13736243210","18185085418","15202326050","13054523216"]
HA;

        $data = json_decode($data,true);
        $a = 0;
        foreach ($data as $k => $v){

            $uid = User::where('phone_num',$v)->value('id');
            $summaryInfo = RepaySummary::where('uid',$uid)->first();
            $recordMoney = RepayRecordMoney::where('summary_id',$summaryInfo->id)->where('period',0)->where('status',4)->first();

            if($recordMoney){
                $data = [
                    'loanId' => $summaryInfo->loan_id,
                ];
                $result = MoneyPlatformRequestFacade::getRepayPlan($data);
                dd($result);
                if(isset($result['data'])){
                    $info = end($result['data']);
                    if($info['status'] == 'NJ'){
                        $recordMoney->lending_money = $info['interestAmount']; //利息
                        $recordMoney->fines_money = $info['penaltyAmount'];//罚息
                        $recordMoney->repayment_money = $info['serviceAmount'];//手续费
                        $recordMoney->save();
                    }
                }
                $a++;
            }
        }
        $this->info($a."条数据更新完毕");
    }


    /**
     * Description:修复问题1
     * Author:lijiafei
     */
    public function setRepayMoney8(){
        $data = <<<HA
[{"phone":"18936331783","period":"1\r"},{"phone":"18876594366","period":"1\r"},{"phone":"18571574987","period":"1\r"},{"phone":"15503999156","period":"1\r"},{"phone":"15894885678","period":"1\r"},{"phone":"15100665596","period":"1\r"},{"phone":"15875569007","period":"2\r"},{"phone":"18294672867","period":"1\r"},{"phone":"13615493234","period":"1\r"},{"phone":"13961271035","period":"1\r"},{"phone":"13566702331","period":"1\r"},{"phone":"13827217518","period":"1\r"},{"phone":"13473299536","period":"2\r"},{"phone":"18057161580","period":"2\r"},{"phone":"15045421518","period":"2\r"},{"phone":"15963433763","period":"2\r"},{"phone":"18508405985","period":"1\r"},{"phone":"15960445949","period":"2\r"},{"phone":"18933922506","period":"1\r"},{"phone":"13850788320","period":"1\r"},{"phone":"18757631299","period":"2\r"},{"phone":"13720406662","period":"1\r"},{"phone":"18949840478","period":"1\r"},{"phone":"15697349105","period":"1\r"},{"phone":"13909119952","period":"2\r"},{"phone":"13759162989","period":"5\r"},{"phone":"13839788287","period":"2\r"},{"phone":"13753999911","period":"1\r"},{"phone":"15287275665","period":"1\r"},{"phone":"13520653212","period":"2\r"},{"phone":"13948725224","period":"2\r"},{"phone":"15868487937","period":"2\r"},{"phone":"15922657102","period":"4\r"},{"phone":"15129778692","period":"1\r"},{"phone":"13107860117","period":"1\r"},{"phone":"13902283470","period":"1\r"},{"phone":"13196011371","period":"2\r"},{"phone":"13802406722","period":"1\r"},{"phone":"13611365473","period":"4\r"},{"phone":"13704284961","period":"1\r"},{"phone":"18620186309","period":"4\r"},{"phone":"13456647878","period":"2\r"},{"phone":"15991858630","period":"1\r"},{"phone":"13536268768","period":"2\r"},{"phone":"18736055357","period":"2\r"},{"phone":"15975015852","period":"2\r"},{"phone":"13972470453","period":"4\r"},{"phone":"18364479779","period":"2\r"},{"phone":"18605000970","period":"1\r"},{"phone":"18196586190","period":"1\r"},{"phone":"13681963980","period":"2\r"},{"phone":"13404226810","period":"2\r"},{"phone":"13591836014","period":"2\r"},{"phone":"13555800527","period":"2\r"},{"phone":"15623041396","period":"2\r"},{"phone":"13988911227","period":"5\r"},{"phone":"15966567968","period":"2\r"}]
HA;
        $data = json_decode(str_replace("\r",'',$data),true);

        $a = 0;
        foreach ($data as $k => $v){
            $uid = User::where('phone_num',$v['phone'])->value('id');
            $summaryInfo = RepaySummary::where('uid',$uid)->first();
            $recordMoney = RepayRecordMoney::where('summary_id',$summaryInfo->id)->where('period',$v['period'])->where('status',4)->first();

            try{
                DB::beginTransaction();
                if($recordMoney){
                    $data = [
                        'loanId' => $summaryInfo->loan_id,
                        'period' => $v['period']
                    ];
                    $result = MoneyPlatformRequestFacade::getRepayPlan($data);
                    $info = $result['data'];
                    if(isset($info)){
                        $recordMoney->lending_money = $info['interestAmount']; //利息
                        $recordMoney->fines_money = $info['penaltyAmount'];//罚息
                        $recordMoney->repayment_money = $info['serviceAmount'];//手续费
                        $recordMoney->repay_type = 2;//修改状态
                        $recordMoney->save();
                    }
                }

                $recordCommon = RepayRecordCommon::where('summary_id',$summaryInfo->id)->where('period',$v['period'])->where('status',4)->first();
                if($recordCommon){
                    if($recordCommon->fines_money){
                        $recordCommon->relief_amount = $recordCommon->fines_money;
                        $recordCommon->fines_money = 0;
                    }
                    $recordCommon->repay_type = 2;
                    $recordCommon->save();
                }

                $recode = RepayRecord::where('summary_id',$summaryInfo->id)->where('period',$v['period'])->where('status',4)->first();
                if($recode){
                    $recode->repay_type = 2;
                    $recode->save();
                }

                DB::commit();
            }catch (\Exception $e){
                DB::rollBack();
            }

        }
        $this->info($a."条数据更新完毕");
    }

    /**
     * Description:修复问题1
     * Author:lijiafei
     */
    public function setRepayMoney81(){
        $data = <<<HA
[{"phone":"18936331783","period":"1\r"},{"phone":"18876594366","period":"1\r"},{"phone":"18571574987","period":"1\r"},{"phone":"15503999156","period":"1\r"},{"phone":"15894885678","period":"1\r"},{"phone":"15100665596","period":"1\r"},{"phone":"15875569007","period":"2\r"},{"phone":"18294672867","period":"1\r"},{"phone":"13615493234","period":"1\r"},{"phone":"13961271035","period":"1\r"},{"phone":"13566702331","period":"1\r"},{"phone":"13827217518","period":"1\r"},{"phone":"13473299536","period":"2\r"},{"phone":"18057161580","period":"2\r"},{"phone":"15045421518","period":"2\r"},{"phone":"15963433763","period":"2\r"},{"phone":"18508405985","period":"1\r"},{"phone":"15960445949","period":"2\r"},{"phone":"18933922506","period":"1\r"},{"phone":"13850788320","period":"1\r"},{"phone":"18757631299","period":"2\r"},{"phone":"13720406662","period":"1\r"},{"phone":"18949840478","period":"1\r"},{"phone":"15697349105","period":"1\r"},{"phone":"13909119952","period":"2\r"},{"phone":"13759162989","period":"5\r"},{"phone":"13839788287","period":"2\r"},{"phone":"13753999911","period":"1\r"},{"phone":"15287275665","period":"1\r"},{"phone":"13520653212","period":"2\r"},{"phone":"13948725224","period":"2\r"},{"phone":"15868487937","period":"2\r"},{"phone":"15922657102","period":"4\r"},{"phone":"15129778692","period":"1\r"},{"phone":"13107860117","period":"1\r"},{"phone":"13902283470","period":"1\r"},{"phone":"13196011371","period":"2\r"},{"phone":"13802406722","period":"1\r"},{"phone":"13611365473","period":"4\r"},{"phone":"13704284961","period":"1\r"},{"phone":"18620186309","period":"4\r"},{"phone":"13456647878","period":"2\r"},{"phone":"15991858630","period":"1\r"},{"phone":"13536268768","period":"2\r"},{"phone":"18736055357","period":"2\r"},{"phone":"15975015852","period":"2\r"},{"phone":"13972470453","period":"4\r"},{"phone":"18364479779","period":"2\r"},{"phone":"18605000970","period":"1\r"},{"phone":"18196586190","period":"1\r"},{"phone":"13681963980","period":"2\r"},{"phone":"13404226810","period":"2\r"},{"phone":"13591836014","period":"2\r"},{"phone":"13555800527","period":"2\r"},{"phone":"15623041396","period":"2\r"},{"phone":"13988911227","period":"5\r"},{"phone":"15966567968","period":"2\r"}]
HA;

        $data = json_decode(str_replace("\r",'',$data),true);
        $a = 0;
        foreach ($data as $k => $v) {
            $uid = User::where('phone_num', $v['phone'])->value('id');
            $summaryInfo = RepaySummary::where('uid', $uid)->first();
            $recordMoney = RepayRecordMoney::where('summary_id', $summaryInfo->id)->where('period', $v['period'])->where('status', 4)->first();
            $recordCommon = RepayRecordCommon::where('summary_id',$summaryInfo->id)->where('period',$v['period'])->where('status',4)->first();
            if($recordMoney->repay_type == 2  &&  $recordCommon->repay_type == 2){
                $recode = RepayRecord::where('summary_id',$summaryInfo->id)->where('period',$v['period'])->where('status',4)->first();
                if($recode){
                    $recode->repay_type = 2;
                    $recode->save();
                }
            }
        }
        $this->info('执行结束');

    }

    /**
     * Description:修复问题7
     * Author:lijiafei
     */
    public function setRepayMoney7(){
        $data = <<<HA
[{"phone":"A0220181215447761","money":"1067.09"},{"phone":"A0220181210428215","money":"1067.09"},{"phone":"A0220181114345722","money":"502.78 "},{"phone":"A0220181207412490","money":"700.49 "},{"phone":"A0220181119369634","money":"386.76"},{"phone":"A0220181219463005","money":"1067.09 "},{"phone":"A0220190121510170","money":"1037.68 "},{"phone":"A0220181211430354","money":"2288.82 "},{"phone":"A0220181126382179","money":"681.19 "},{"phone":"A0220181126383602","money":"681.19 "},{"phone":"A0220181126383698","money":"786.00 "},{"phone":"A0220181027316392","money":"850.86 "},{"phone":"A0220181126384145","money":"681.19 "},{"phone":"A0220181027316942","money":"232.06 "},{"phone":"A0220181015287789","money":"1422.63 "},{"phone":"A0220181028318019","money":"386.76 "},{"phone":"A0220181128386921","money":"786.00 "},{"phone":"A0220181123377841","money":"681.19 "},{"phone":"A0220181129388508","money":"786.00 "},{"phone":"A0220181129388698","money":"1231.25 "},{"phone":"A0220181124378920","money":"786.00 "},{"phone":"A0220181129389141","money":"681.19 "},{"phone":"A0220181129389898","money":"786.00 "},{"phone":"A0220181130390776","money":"786.00 "},{"phone":"A0220181130390797","money":"681.19 "},{"phone":"A0220181130391272","money":"786.00 "},{"phone":"A0220181130391380","money":"209.60 "},{"phone":"A0220181125381465","money":"681.19 "},{"phone":"A0220181130391533","money":"492.51 "},{"phone":"A0220190126541326","money":"1009.09 "},{"phone":"A0220190128553424","money":"776.23 "},{"phone":"A0220190130566866","money":"1009.09 "},{"phone":"A0220190130569017","money":"155.25 "},{"phone":"A0220190130570128","money":"310.49 "},{"phone":"A0220180703188240","money":"620.99 "},{"phone":"A0220181031325730","money":"386.76 "},{"phone":"A0220181031326496","money":"773.51 "},{"phone":"A0220190130568570","money":"776.23 "},{"phone":"A0220190131574250","money":"2106.42 "},{"phone":"A0220190127549852","money":"2106.42 "},{"phone":"A0220190124531129","money":"1862.95 "}]
HA;
        $data = json_decode($data,true);
        $a = 0;
        foreach ($data as $k => $v){
            $loan_request_id = UserLoanRequest::where('trans_id',$v['phone'])->value('id');
            if($loan_request_id){
                $v['money'] = str_replace(" ","",$v['money']);
                $summaryInfo = RepaySummary::where('loan_request_id',$loan_request_id)->first();
                $money = bcmul($v['money'],100);
                $recordInfo = RepayRecord::where('summary_id',$summaryInfo->id)->where('amount',$money)->where('period','<>',0)->first();
                if($recordInfo){
                    $p = [
                        'loanId' => $summaryInfo->loan_id,
                        'period' => $recordInfo->period
                    ];
                    $result = MoneyPlatformRequestFacade::getRepayPlan($p);
                    if(isset($result['data'])){
                        $result = $result['data'];
                        $is_success = RepayRecordMoney::getMoneyPlanStatus($result['status']);
                        if(!$is_success){
//                            dump($summaryInfo->loan_channel);
//                            //修改状态
                            try{
                                DB::beginTransaction();
                                UserGlobal::where('uid',$summaryInfo->uid)->update(['global_status' => 61]);
                                $updateSummary = [
                                    'period' => $recordInfo->period,
                                    'status' => RepaySummary::STATUS_ONE,
                                ];
                                RepaySummary::where('id', $recordInfo->summary_id)->update($updateSummary); //summary表
                                $updateRecord = [
                                    'status' => RepayRecord::STATUS_ONE,
                                    'repay_date' => null, //实际还款日期
                                    'repay_type' => 2,//状态改为销账
                                    'xz_status' => 1
                                ];
                                //记录总表
                                RepayRecord::where('id', $recordInfo->id)->update($updateRecord);
                                $updateMoney = [
                                    'status' => RepayRecord::STATUS_ONE,
                                    'apply_time' => null, //实际还款日期
                                    'status_time' => null, //实际还款日期
                                    'repay_date' => null, //实际还款日期
                                    'repay_type' => 2,//状态改为销账

                                ];
                                RepayRecordMoney::where('record_id', $recordInfo->id)->update($updateMoney);
                                DB::commit();
                            }catch (\Exception $e){
                                DB::rollBack();
                            }
                        }
                    }
                }
            }
        }
        $this->info('更新完成');
    }















}
